import { createRouter, createWebHistory } from 'vue-router'; //createWebHashHistory
import SystemSetRouter from '../views/system_set/router';
import TestRouter from '../views/test/router';
import LabRouter from '../views/lab_sys/router';
import SqlViewRouter from '../views/sql_view/router';
import EmrRouter from '../views/emr_rate/router';
import InvRouter from '../views/inv_sys/router';
import TaskRouter from '../views/task/router';
import ReportRouter from '../views/system_set/reports/router';
import workSysRouter from '../views/work_sys/router';
import IntRouter from '../views/interface/router';
import KnoRouter from '../views/kno_sys/router';
import StandardRouter from '../views/standard_set/router';
import PoctRouter from '../views/poct/router';
import QiIndexRouter from '../views/lab_sys/qi_set/router';

import { AppStore } from '@/stores/store';
import { ElMessage } from 'element-plus';

import axios from 'axios';

const Axios = axios.create();
Axios.defaults.baseURL = (window as any).apiUrl.VITE_SERVER_URL;
Axios.defaults.timeout = 60000;

let routers = [
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/HomePage.vue')
  },
  {
    path: '/messages',
    name: 'messages',
    component: () => import('../views/Messages.vue')
  },
  {
    path: '/settings',
    name: 'settings',
    component: () => import('../views/Settings.vue')
  },

  {
    path: '/todolist',
    name: 'todolist',
    component: () => import('../views/TodoList.vue')
  },
  {
    path: '/wkltByHis',
    name: 'wkltByHis',
    component: () => import('@/views/lab_sys/lab_set/wkltByHis.vue')
  },
  {
    path: '/ssreport',
    name: 'ssreport',
    component: () => import('@/views/lab_sys/ssreport/HomePageAcross.vue')
  },{
    path: '/ssreportVertical',
    name: 'ssreportVertical',
    component: () => import('@/views/lab_sys/ssreport/HomePageVertical.vue')
  },
  {
    path: '/criReportChk',
    name: 'criReportChk',
    component: () => import('@/views/lab_sys/cri_set/CriReportChk.vue')
  },
  {
    path: '/demo',
    name: 'demo',
    component: () => import('../views/Demo.vue')
  },
  {
    path: '/equipment2Copy',
    name: 'equipment2Copy',
    component: () => import('../views/EquiptHome2Copy.vue')
  },
  {
    path: '/criCockpit',
    name: 'criCockpit',
    component: () => import('../views/CriCockpit.vue')
  },
  {
    path: '/criReportReceive',
    name: 'criReportReceive',
    component: () => import('@/views/lab_sys/cri_set/CriReportReceive.vue')
  },
  {
    path: '/criReportHandle',
    name: 'criReportHandle',
    component: () => import('@/views/lab_sys/cri_set/CriReportHandle.vue')
  }
];
routers = routers.concat(SystemSetRouter);
routers = routers.concat(TestRouter);
routers = routers.concat(LabRouter);
routers = routers.concat(TaskRouter);
routers = routers.concat(ReportRouter);
routers = routers.concat(workSysRouter);
routers = routers.concat(IntRouter);
routers = routers.concat(InvRouter);
routers = routers.concat(SqlViewRouter);
routers = routers.concat(EmrRouter);
routers = routers.concat(KnoRouter);
routers = routers.concat(StandardRouter);
routers = routers.concat(QiIndexRouter);
routers = routers.concat(PoctRouter);

function getLogBaseUrl() {  
  let logBaseUrl: any = '/labmaininfo';
  if (localStorage.getItem('logBaseUrl')) {
    logBaseUrl = localStorage.getItem('logBaseUrl');
  }  
  return logBaseUrl;
}

const router = createRouter({
  history: createWebHistory(), //createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'layout',
      component: () => import('../views/LayoutV1.vue'),
      redirect: getLogBaseUrl,
      children: routers
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue')
    },
    {
      path: '/homepage',
      name: 'homepage',
      component: () => import('../views/HomePage.vue')
    },
    {
      path: '/homepage1',
      name: 'homepage1',
      component: () => import('../views/HomePage1.vue')
    },
    {
      path: '/layoutint',
      name: 'layoutint',
      component: () => import('../views/LayoutInt.vue'),
      redirect: '/inthomepage',
      children: routers
    }
  ]
});

async function checkAppNewVersion() {
  const url = `/js/version.json?t=${Date.now()}`;
  let res = null;
  try {
    res = await axios.get(url);
  } catch (err) {
    console.error('checkAppNewVersion error: ', err);
  }

  if (!res) {
    return;
  }
  const version = res.data.version;
  if (version && version !== localStorage.getItem('version')) {
    localStorage.setItem('version', version);
    window.location.reload();
  } else {
    //ToDo
  }
}

/**版本校验 */
// 版本监控
const versionCheck = async () => {
  //import.meta.env.MODE 获取的是开发还是生产版本的
  if (import.meta.env.MODE === 'development') return;
  try {
    const response = await axios.get('version.json');
    // eslint-disable-next-line no-undef
    //process.env.VITE__APP_VERSION__  获取环境变量设置的值，判断是否与生成的版本信息一致
    if (__APP_VERSION__ !== response.data.version) {
      // eslint-disable-next-line no-undef
      ElMessage({
        message: '发现新内容，自动更新中...',
        type: 'success',
        showClose: true,
        duration: 1500,
        onClose: () => {
          window.location.reload();
        }
      });
    }
  } catch (error) {
    console.log('验证版本出现异常', error);
  }
};

// 导航守卫
// 使用 router.beforeEach 注册一个全局前置守卫，判断用户是否登陆
router.beforeEach(async (to, from, next) => {
  await versionCheck();
  // 除了跳转到'/'之外，都进行版本号对比
  // if (from.path !== '/') {
  //   checkAppNewVersion();
  // }
  const token = localStorage.getItem('token');
  if (to.path === '/login' || to.path === '/wkltByHis' || to.path === '/printBarcode' || to.path === '/printBarcodePre' || to.path === '/criReportChk'|| to.path === '/criReportReceive'|| to.path === '/criReportHandle'|| to.path === '/ssreport' || to.path === '/ssreportVertical') {
    next();
  } else if (to.query.token && (!token || token == 'undefined')) {
    console.log('单点登录访问页面');
    let store = AppStore();
    const url = '/public/user/getSSODataByToken';
    const params = {
      url: (window as any).apiUrl.VUE_APP_INTERFACE_URL + '/sso/checkToken',
      token: to.query.token
    };
    Axios.get(url, { params: params })
      .then((res: any) => {
        console.log(res.data.data);
        if (res.data.data) {
          store.setToken(res.data.data.token);
          const user: any = {
            id: res.data.data.user.id,
            hisEmployeeCode: res.data.data.user.hisEmployeeCode,
            realname: res.data.data.user.realname,
            tel: res.data.data.user.tel,
            username: res.data.data.user.username,
            orgId: res.data.data.user.orgId,
            //role:res.data.user.UserRoles[0].roleId,
            orgName: res.data.data.user.organization ? res.data.data.user.organization.name : '',
            orgCode: res.data.data.user.organization ? res.data.data.user.organization.code : '',
            orgType: res.data.data.user.organization ? res.data.data.user.organization.type : '',
            layoutSkin: res.data.data.user.layoutSkin,
            systemList: res.data.data.user.SystemList,
            orgList: res.data.data.user.orgList
          };
          store.setUserInfo(user);
          localStorage.setItem('moduleId', '1716657789982969857');
          store.setRoleModel(res.data.data.auth.modules);
          store.setModuleMenuMap(res.data.data.auth.moduleMenuMap);
          store.setModulePointMap(res.data.data.auth.modulePointCodeMap);
          store.setRptGroupList(res.data.data.auth.rptGroupList);
          store.setInstrSetupList(res.data.data.auth.instrSetupList);
          next();
        } else {
          next('/login');
        }
      })
      .catch((err: any) => {
        next('/login');
      });
  } else if (!to.query.token && (!token || token == 'undefined')) {
    next('/login');
  } else {
    next();
  }
  // else {
  //   if (!token) {
  //     next('/login');
  //   } else {
  //     next();
  //   }
  // }
});

export default router;
